﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Threading;

namespace XMK.Tadong.Web.TJ
{
    public class DownLoad
    {
        public DownLoad()
        {

        }

        /// 根据用户提供的条件下载相关的文件
        /// </summary>
        /// <param name="_Request">客户端的请求</param>
        /// <param name="_Response">服务器端的发送</param>
        /// <param name="_fileName">文件名称</param>
        /// <param name="_fullPath">完整文件路径名</param>
        /// <param name="_speed">下载速度调节-根据服务器来控制</param>
        /// <returns></returns>
        public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
        {
            try
            {
                FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    long fileLength = myFile.Length;
                    long startBytes = 0;

                    string strExt = Path.GetExtension(_fullPath);


                    _fileName = _fileName + strExt;
                    _fileName = Path.GetDirectoryName(_fullPath) + "\\" + _fileName;

                    int pack = 10240; //10K bytes
                    int sleep = (int)Math.Floor(Convert.ToDecimal(1000 * pack / _speed)) + 1;



                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1,fileLength));
                    }
                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
                     
                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = (int)Math.Floor(Convert.ToDecimal((fileLength - startBytes) / pack) )+ 1;

                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(pack));
                            Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                    //File.Delete(_fullPath);
                    _Response.Flush();
                    SysHelper.CloseWin(_Response);
                }
                catch (Exception er)
                {
                    throw;
                }
                finally
                {
                    br.Close();
                    myFile.Close();

                }
            }
            catch (Exception er)
            {
                //Session["ErrorInfo"] = er.ToString();
                throw;
            }
            return true;
        }
    }
}